<template>
  <div class="calendar-container">
    <el-row :gutter="20">
      <!-- 左侧筛选面板 -->
      <el-col :span="6">
        <div class="filter-panel">
          <div class="panel-header">
            <h3>请选择日历类型</h3>
            <el-button 
              type="primary" 
              size="small" 
              @click="showTypeManage"
            >
              管理类型
            </el-button>
          </div>
          <div class="filter-list">
            <div v-for="(item, index) in filterItems" :key="index" class="filter-item">
              <el-checkbox v-model="item.checked" :style="{ color: item.color }">
                {{ item.label }}
              </el-checkbox>
              <div class="color-block" :style="{ backgroundColor: item.color }"></div>
            </div>
          </div>
          <el-button type="primary" class="filter-button" @click="applyFilters">确定</el-button>
        </div>
      </el-col>

      <!-- 右侧日历主体 -->
      <el-col :span="18">
        <div class="calendar-main">
          <div class="calendar-header">
            <div class="header-left">
              <el-button-group>
                <el-button @click="prevMonth">
                  <el-icon><ArrowLeft /></el-icon>
                </el-button>
                <el-button @click="nextMonth">
                  <el-icon><ArrowRight /></el-icon>
                </el-button>
              </el-button-group>
              <el-button @click="goToday" class="today-btn">今天</el-button>
            </div>
            <h2 class="current-date">{{ currentYear }}年 {{ currentMonth }}月</h2>
          </div>

          <!-- 日历表格 -->
          <el-table 
            :data="calendarData" 
            :border="true"
            :cell-style="{ padding: '0', position: 'relative' }"
            class="calendar-table"
          >
            <el-table-column 
              v-for="day in weekDays" 
              :key="day" 
              :label="day"
              align="center"
            >
              <template #default="scope">
                <div 
                  class="calendar-cell" 
                  :class="getCellClass(scope.row[day])"
                  @click="handleDateClick(scope.row[day].fullDate)"
                >
                  <span class="date-number">{{ scope.row[day].date }}</span>
                  <div class="events-list">
                    <div 
                      v-for="event in scope.row[day].events" 
                      :key="event.id"
                      class="event-item"
                      :class="{
                        'continue-left': !event.isStart && event.isContinuous,
                        'continue-right': !event.isEnd && event.isContinuous,
                        'single-day': !event.isContinuous,
                        'continuous-event': event.isContinuous,
                        'event-start': event.isStart && event.isContinuous,
                        'event-end': event.isEnd && event.isContinuous,
                        'event-middle': !event.isStart && !event.isEnd && event.isContinuous
                      }"
                      :style="{
                        backgroundColor: event.color,
                        zIndex: event.isContinuous ? 2 : 1
                      }"
                      @click.stop="handleEventClick(event)"
                    >
                      {{ event.isStart || !event.isContinuous ? event.content : '' }}
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>

    <!-- 新增/编辑事件对话框 -->
    <el-dialog 
      :title="dialogType === 'add' ? '新增事件' : '编辑事件'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form ref="eventFormRef" :model="eventForm" :rules="eventRules" label-width="80px">
        <el-form-item label="时间段" required>
          <el-row :gutter="10">
            <el-col :span="11">
              <el-form-item prop="start_date">
                <el-date-picker 
                  v-model="eventForm.start_date"
                  type="date"
                  placeholder="开始日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">至</el-col>
            <el-col :span="11">
              <el-form-item prop="end_date">
                <el-date-picker 
                  v-model="eventForm.end_date"
                  type="date"
                  placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disableEndDate"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="eventForm.type" placeholder="选择事件类型" @change="handleTypeChange">
            <el-option 
              v-for="item in filterItems"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <div class="color-picker-wrapper">
            <el-color-picker 
              v-model="eventForm.color" 
              show-alpha
              :predefine="predefineColors"
            />
            <span class="color-value">{{ eventForm.color }}</span>
          </div>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="eventForm.content" 
            type="textarea" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitEvent">确定</el-button>
      </template>
    </el-dialog>

    <!-- 类型管理对话框 -->
    <el-dialog
      title="管理事件类型"
      v-model="typeDialogVisible"
      width="600px"
    >
      <div class="type-manage-header">
        <el-button type="primary" @click="handleAddType">添加类型</el-button>
      </div>
      
      <el-table :data="filterItems" style="width: 100%">
        <el-table-column prop="label" label="类型名称" width="180">
          <template #default="{ row }">
            <template v-if="row.editing">
              <el-input v-model="row.label" size="small" />
            </template>
            <span v-else>{{ row.label }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="color" label="颜色" width="180">
          <template #default="{ row }">
            <template v-if="row.editing">
              <el-color-picker v-model="row.color" size="small" />
            </template>
            <div v-else class="color-preview" :style="{ backgroundColor: row.color }">
              {{ row.color }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作">
          <template #default="{ row }">
            <template v-if="row.editing">
              <el-button link type="primary" @click="handleSaveType(row)">保存</el-button>
              <el-button link type="info" @click="handleCancelEdit(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button link type="primary" @click="handleEditType(row)">编辑</el-button>
              <el-button link type="danger" @click="handleDeleteType(row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/utils/http';  // 替换axios

const currentYear = ref(new Date().getFullYear());
const currentMonth = ref(new Date().getMonth() + 1);
const viewType = ref('month');
const events = ref([]);

const weekDays = ['一', '二', '三', '四', '五', '六', '日'];

const filterItems = ref([]); // 改为空数组初始化

const dates = computed(() => {
  const firstDay = new Date(currentYear.value, currentMonth.value - 1, 1);
  const lastDay = new Date(currentYear.value, currentMonth.value, 0);
  const days = [];

  const firstDayWeek = firstDay.getDay() || 7;
  for (let i = firstDayWeek - 1; i > 0; i--) {
    const date = new Date(firstDay);
    date.setDate(date.getDate() - i);
    days.push(date);
  }

  for (let i = 1; i <= lastDay.getDate(); i++) {
    days.push(new Date(currentYear.value, currentMonth.value - 1, i));
  }

  const remainingDays = 42 - days.length;
  for (let i = 1; i <= remainingDays; i++) {
    const date = new Date(lastDay);
    date.setDate(date.getDate() + i);
    days.push(date);
  }

  return days;
});

const isToday = (date) => {
  const today = new Date();
  return date.getDate() === today.getDate() &&
         date.getMonth() === today.getMonth() &&
         date.getFullYear() === today.getFullYear();
};

const getEventsForDate = (date) => {
  const formattedDate = formatDate(new Date(date));
  return events.value.filter(event => {
    // 检查事件是否在当前日期范围内
    return formattedDate >= event.start_date && formattedDate <= event.end_date;
  }).map(event => {
    // 确定事件是否跨天
    const isContinuous = event.start_date !== event.end_date;
    // 确定是否是开始日期
    const isStart = formattedDate === event.start_date;
    // 确定是否是结束日期
    const isEnd = formattedDate === event.end_date;
    
    return {
      ...event,
      isStart,
      isEnd,
      isContinuous,
      // 为了调试
      formattedDate,
      eventStartDate: event.start_date,
      eventEndDate: event.end_date
    };
  });
};

// 添加日期比较辅助函数
const isSameDate = (date1, date2) => {
  if (!date1 || !date2) return false;
  
  if (typeof date1 === 'string') {
    date1 = new Date(date1);
  }
  
  if (typeof date2 === 'string') {
    date2 = new Date(date2);
  }
  
  return date1.getFullYear() === date2.getFullYear() &&
         date1.getMonth() === date2.getMonth() &&
         date1.getDate() === date2.getDate();
};

const prevMonth = () => {
  if (currentMonth.value === 1) {
    currentYear.value--;
    currentMonth.value = 12;
  } else {
    currentMonth.value--;
  }
  fetchEvents();
};

const nextMonth = () => {
  if (currentMonth.value === 12) {
    currentYear.value++;
    currentMonth.value = 1;
  } else {
    currentMonth.value++;
  }
  fetchEvents();
};

const applyFilters = () => {
  fetchEvents();
};

const fetchEvents = async () => {
  try {
    // 添加防御性检查
    const checkedFilters = filterItems.value?.filter(item => item?.checked)?.map(item => item?.label) || [];

    const data = await http.get('/calendar/events', {
      params: {
        year: currentYear.value,
        month: currentMonth.value,
        filter: checkedFilters
      }
    });
    
    events.value = Array.isArray(data) ? data : [];
    
    if(!events.value.length) {
      ElMessage.info('当前月份暂无事件数据');
    }
  } catch (error) {
    console.error('获取事件失败:', error);
    ElMessage.error(error.message || '获取事件失败');
    events.value = []; // 确保错误时设置为空数组
  }
};

const fetchCalendarTypes = async () => {
  try {
    const data = await http.get('/calendar/types');
    // 确保data存在且为数组
    if (data && Array.isArray(data)) {
      filterItems.value = data.map(item => ({
        ...item,
        checked: true // 添加checked属性
      }));
    } else {
      filterItems.value = [
        { label: '请添加事件类型-1', checked: true, color: '#FF69B4' },
        { label: '请添加事件类型-2', checked: true, color: '#FFB6C1' },
        { label: '请添加事件类型-3', checked: true, color: '#FFD700' },
        // ... 其他默认选项
      ];
      ElMessage.info('使用默认日历类型数据');
    }
  } catch (error) {
    console.error('获取日历类型失败:', error);
    ElMessage.error(error.message || '获取日历类型失败');
    // 设置默认值
    filterItems.value = [
      { label: '新股上市', checked: true, color: '#FF69B4' },
      { label: '新股申购', checked: true, color: '#FFB6C1' },
      { label: '可转债', checked: true, color: '#FFD700' },
      // ... 其他默认选项
    ];
  }
};

onMounted(async () => {
  await fetchCalendarTypes(); // 先获取类型
  await fetchEvents(); // 再获取事件
});

// 状态管理
const dialogVisible = ref(false)
const dialogType = ref('add')
const selectedEvent = ref(null)
const eventFormRef = ref(null)

const eventForm = ref({
  start_date: '',    // 开始日期
  end_date: '',      // 结束日期
  content: '',       // 事件内容
  type: '',          // 事件类型
  color: null        // 事件颜色
})

const eventRules = {
  start_date: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  end_date: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  type: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入事件内容', trigger: 'blur' }]
}

// 禁用结束日期早于开始日期
const disableEndDate = (date) => {
  if (!eventForm.value.start_date) return false
  return date < new Date(eventForm.value.start_date)
}

// 事件处理函数
const handleDateClick = (date) => {
  dialogType.value = 'add'
  selectedEvent.value = null
  eventForm.value = {
    start_date: formatDate(date),
    end_date: formatDate(date),  // 默认结束日期同开始日期
    type: '',
    content: '',
    color: ''
  }
  dialogVisible.value = true
}

const handleEventClick = (event) => {
  dialogType.value = 'edit'
  selectedEvent.value = event
  eventForm.value = { 
    ...event,
    start_date: event.start_date,
    end_date: event.end_date 
  }
  dialogVisible.value = true
}

const handleTypeChange = (type) => {
  const selectedType = filterItems.value.find(item => item.label === type)
  if (selectedType) {
    eventForm.value.color = selectedType.color
  }
}

const handleSubmitEvent = async () => {
  if (!eventFormRef.value) return
  
  await eventFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          start_date: eventForm.value.start_date,
          end_date: eventForm.value.end_date,
          content: eventForm.value.content.trim().substring(0, 500),
          type: eventForm.value.type.trim().substring(0, 50),
          color: eventForm.value.color || null
        };

        if (dialogType.value === 'add') {
          await http.post('/calendar/events', submitData);
          ElMessage.success('添加成功');
        } else {
          submitData.id = selectedEvent.value.id;
          await http.put(`/calendar/events/${selectedEvent.value.id}`, submitData);
          ElMessage.success('更新成功');
        }
        
        dialogVisible.value = false;
        fetchEvents();
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error(error.message || '操作失败');
      }
    }
  })
}

// 工具函数
const formatDate = (date) => {
  if (!date) return '';
  
  if (typeof date === 'string') {
    // 如果已经是YYYY-MM-DD格式，直接返回
    if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
      return date;
    }
    date = new Date(date);
  }
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const calendarData = computed(() => {
  const weeks = [];
  let currentWeek = {};
  const today = new Date();
  
  dates.value.forEach((date, index) => {
    const dayName = weekDays[index % 7];
    const isCurrentMonth = date.getMonth() === currentMonth.value - 1;
    
    currentWeek[dayName] = {
      date: date.getDate(),
      isCurrentMonth,
      isToday: isToday(date),
      events: getEventsForDate(date),
      fullDate: date
    };

    if (index % 7 === 6) {
      weeks.push(currentWeek);
      currentWeek = {};
    }
  });

  return weeks;
});

const getCellClass = (cell) => {
  return {
    'is-today': cell.isToday,
    'is-other-month': !cell.isCurrentMonth
  };
};

const goToday = () => {
  const today = new Date();
  currentYear.value = today.getFullYear();
  currentMonth.value = today.getMonth() + 1;
  fetchEvents();
};

const predefineColors = [
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  '#ff69b4'
]

// 类型管理相关状态
const typeDialogVisible = ref(false)
const typeBeforeEdit = ref({}) // 保存编辑前的值用于取消编辑

// 类型管理方法
const showTypeManage = () => {
  typeDialogVisible.value = true
}

const handleAddType = () => {
  const newType = {
    label: '新建类型',
    color: '#409EFF',
    checked: true,
    editing: true,
    isNew: true
  }
  filterItems.value.unshift(newType)
}

const handleEditType = (row) => {
  typeBeforeEdit.value = { ...row }
  row.editing = true
}

const handleCancelEdit = (row) => {
  if (row.isNew) {
    filterItems.value = filterItems.value.filter(item => item !== row)
  } else {
    Object.assign(row, typeBeforeEdit.value)
    row.editing = false
  }
}

const handleSaveType = async (row) => {
  try {
    if (row.isNew) {
      // 添加新类型
      const data = await http.post('/calendar/types', {
        label: row.label,
        color: row.color
      })
      row.id = data.id
      row.isNew = false
    } else {
      // 更新已有类型
      await http.put(`/calendar/types/${row.id}`, {
        label: row.label,
        color: row.color
      })
    }
    row.editing = false
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error(error.message || '保存失败')
  }
}

const handleDeleteType = async (row) => {
  try {
    await ElMessageBox.confirm(
      '删除后相关事件的类型将被设为"其他"，是否继续？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await http.delete(`/calendar/types/${row.id}`)
    filterItems.value = filterItems.value.filter(item => item !== row)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

</script>

<style scoped>
.calendar-container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.filter-panel {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.filter-panel h3 {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
}

.filter-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.filter-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.color-block {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  margin-left: 8px;
}

.filter-button {
  width: 100%;
  margin-top: 20px;
}

.calendar-main {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  padding: 20px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.current-date {
  font-size: 20px;
  font-weight: 500;
}

.calendar-cell {
  position: relative;
  overflow: visible !important; /* 强制允许内容溢出 */
  z-index: 1;
  min-height: 120px;
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.calendar-cell:hover {
  z-index: 3 !important; /* 确保悬停时事件显示在最上层 */
  background-color: var(--el-fill-color-light);
}

.date-number {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  margin-bottom: 4px;
}

.is-today .date-number {
  background-color: var(--el-color-primary);
  color: #fff;
  border-radius: 50%;
}

.is-other-month {
  background-color: var(--el-fill-color-lighter);
  color: var(--el-text-color-secondary);
}

.events-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
  position: relative;
  z-index: 5;
}

.event-item {
  font-size: 12px;
  padding: 2px 8px;
  color: #fff;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: all 0.3s;
  position: relative;
  margin: 1px 0;
  min-height: 22px; /* 确保空事件也有高度 */
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.1);
  z-index: 5; /* 提高层级 */
  border-radius: 4px;
}

/* 单日事件样式 */
.single-day {
  margin: 2px 0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

/* 连续事件的基础样式 */
.continuous-event {
  position: relative;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 连续事件的开始部分 */
.event-start {
  border-radius: 4px 0 0 4px;
  margin-right: 0;
  width: calc(100% + 10px);
  position: relative;
  z-index: 10;
  clip-path: inset(0 -10px 0 0);
}

/* 连续事件的中间部分 */
.event-middle {
  border-radius: 0;
  margin-left: -10px;
  margin-right: 0;
  width: calc(100% + 20px);
  position: relative;
  z-index: 9;
  clip-path: inset(0 -10px 0 -10px);
  border-left: none;
  border-right: none;
}

/* 连续事件的结束部分 */
.event-end {
  border-radius: 0 4px 4px 0;
  margin-left: -10px;
  width: calc(100% + 10px);
  position: relative;
  z-index: 8;
  clip-path: inset(0 0 0 -10px);
  border-left: none;
}

/* 确保表格不会遮挡事件 */
.calendar-table {
  border-collapse: collapse;
  --el-table-border-color: rgba(0, 0, 0, 0.1);
}

/* 确保单元格内容可以溢出 */
.calendar-cell {
  position: relative;
  overflow: visible !important;
  z-index: 1;
}

/* 当鼠标悬停在单元格上时，提高其z-index */
.calendar-cell:hover {
  z-index: 100 !important;
}

/* 确保表格边框不会遮挡事件 */
:deep(.el-table__cell) {
  background-clip: padding-box !important;
}

:deep(.el-table--border) {
  border-color: var(--el-table-border-color);
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid var(--el-table-border-color);
}

/* 确保事件在表格边框之上 */
.events-list {
  position: relative;
  z-index: 5;
}

.text-center {
  text-align: center;
  line-height: 32px;
}

:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
}

:deep(.el-table__header) {
  th {
    background-color: var(--el-fill-color-light);
    font-weight: bold;
  }
}

:deep(.el-table__row) td {
  padding: 0;
}

.color-picker-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.color-value {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.type-manage-header {
  margin-bottom: 20px;
}

.color-preview {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  color: #fff;
  font-size: 12px;
}

/* 确保表格边框更轻，不会干扰事件显示 */
:deep(.el-table--border),
:deep(.el-table--border th.el-table__cell),
:deep(.el-table--border td.el-table__cell) {
  border-color: rgba(0, 0, 0, 0.05) !important;
}
</style>

